package com.smarthealthring.mm.utils;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * 计算单价的工具类 (除法)
 * <p>
 * Created by hewei26 on 2016/6/3.
 */
public class DivideUtils {

    private static final int isYuan = 0;
    private static final int isWan = 1;
    private static final int isYi = 2;

    public static int unitCode;

    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指定精度，以后的数字四舍五入。
     *
     * @param bd    被除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static BigDecimal divide(BigDecimal bd, int scale) {
        BigInteger bt = new BigInteger(bd.toString().contains(".")?bd.toString().substring(0,(bd.toString()).indexOf(".")):bd.toString());
        BigInteger wan = new BigInteger("10000");
        BigInteger yi = new BigInteger("100000000");

        BigDecimal bdDivide = null;

        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        if (bt.compareTo(wan) < 0) {
            //元
            bdDivide = bd;
            unitCode = isYuan;
        } else if (bt.compareTo(yi) < 0) {
            //万
            bdDivide = bd.divide(new BigDecimal(Math.pow(10, 4)), 0, BigDecimal.ROUND_HALF_UP);
            unitCode = isWan;
        } else {
            //亿
            bdDivide = bd.divide(new BigDecimal(Math.pow(10, 8)), scale, BigDecimal.ROUND_HALF_UP);
            unitCode = isYi;
        }
//        bdDivide = new BigDecimal(String.format("%.2f", bdDivide));
        return bdDivide;
    }


    public static String division(double d1, double d2, int len) {// 进行除法运算
        if (d2 != 0) {
            BigDecimal b1 = new BigDecimal(d1);
            BigDecimal b2 = new BigDecimal(d2);
            return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).toString();
        } else {
            return "0";
        }

    }


}
